package com.arpa.wms.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.IterUtil;
import com.arpa.core.web.MediaTypes;
import com.arpa.core.web.Result;
import com.arpa.ntocc.common.common.Page;
import com.arpa.ntocc.common.common.constant.StrConsts;
import com.arpa.ntocc.common.common.exception.ServiceException;
import com.arpa.ntocc.common.common.util.ShipmentWarehouseValidate;
import com.arpa.ntocc.common.common.util.UserUtil;
import com.arpa.ntocc.common.common.util.excel.EasyExcelUtil;
import com.arpa.ntocc.common.security.annotation.NeedLogin;
import com.arpa.wms.domain.consts.CommonConst;
import com.arpa.wms.domain.consts.TipConst;
import com.arpa.wms.domain.dto.ReceiveDTO;
import com.arpa.wms.domain.dto.ReceiveItemExcelDTO;
import com.arpa.wms.domain.entity.*;
import com.arpa.wms.domain.enums.ReceiveTypeEnum;
import com.arpa.wms.domain.vo.*;
import com.arpa.wms.service.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.*;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * <p>
 * 收货 Controller
 * </p>
 *
 * @author LEO
 * @since 2020-08-04
 */
@Api(tags = "收货单")
@RestController
@RequestMapping(value = "/receive", produces = "application/json;charset=UTF-8")
@Log4j2
public class ReceiveController {

    private final IReceiveService iReceiveService;
    private final IDeliveryService iDeliveryService;
    private final IDeliveryItemService iDeliveryItemService;
    @Autowired
    private IPutawayService iPutawayService;

    @Autowired
    private IInboundService iInboundService;


    public ReceiveController(IReceiveService iReceiveService,
                             IDeliveryService iDeliveryService,
                             IDeliveryItemService iDeliveryItemService
    ) {
        this.iReceiveService = iReceiveService;
        this.iDeliveryService = iDeliveryService;
        this.iDeliveryItemService = iDeliveryItemService;
    }

    /**
     * 获取 收货 列表
     *
     * @param receiveDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "收货单列表", notes = "收货单列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = ReceiveVO.class))
    @NeedLogin
    @GetMapping()
    public Result list(ReceiveDTO receiveDTO, HttpServletRequest request) {
        try {
            //校验授权仓库code和货主code不能为空
            Map<String, List<String>> authMap = ShipmentWarehouseValidate.validateShipmentCodesAndWarehouseCodes();
            //登录账号授权的仓库过滤
            receiveDTO.setWarehouseCodes(authMap.get(CommonConst.WAREHOUSE_CODES));
            //登录账号授权的货主过滤
            receiveDTO.setShipmentCodes(authMap.get(CommonConst.SHIPMENT_CODES));
            //登录账号所在组织机构过滤
            receiveDTO.setGroupCode(UserUtil.getBranchCode());

            ReceiveVO receiveVOSum = iReceiveService.queryListTotal(receiveDTO);
            List<ReceiveVO> receiveVOList = iReceiveService.queryList(receiveDTO);


            Page returnPage = new Page(receiveDTO.getPageNum(), receiveDTO.getPageSize());
            returnPage.setRecords(receiveVOList);
            if (receiveVOSum != null) {
                returnPage.setTotal(receiveVOSum.getTotal());
            }
            returnPage.setSumObject(receiveVOSum);
            return Result.ok().data(returnPage);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 添加 收货
     *
     * @param entity  Receive
     * @param request
     * @return
     */
    @ApiOperation(value = "新增收货单 ", notes = "新增收货单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping()
    public Result create(@Validated(Receive.Save.class) Receive entity, HttpServletRequest request) {
        try {

            if (IterUtil.isEmpty(entity.getReceiveItemList())) {
                return Result.error("新增收货单失败，收货商品为空！");
            }
            entity.setGroupCode(UserUtil.getBranchCode());
            List<ReceiveItem> receiveItems = entity.getReceiveItemList().stream()
                    .map(e -> e.setGroupCode(UserUtil.getBranchCode())).collect(Collectors.toList());
            entity.setReceiveItemList(receiveItems);
            iReceiveService.save(entity);
            return Result.ok("添加成功");
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取收货详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取收货详情", notes = "获取收货详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "收货code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Receive.class))
    @NeedLogin
    @GetMapping(value = "/{code}")
    public Result receive(@PathVariable String code, HttpServletRequest request) {
        try {
            ReceiveVO entityVO = iReceiveService.getOneVOByCode(code);
            return Result.ok().data(entityVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 保存收货登记
     *
     * @param entity  收货
     * @param request
     * @return
     */
    @ApiOperation(value = "保存收货登记", notes = "保存收货登记")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping()
    public Result update(Receive entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error("code不能为空");
        }
        entity.setGroupCode(UserUtil.getBranchCode());
        int updateNum = iReceiveService.updateByCode(entity);
        if (updateNum == 0) {
            return Result.error("没有更新数据！code:" + entity.getCode());
        } else {
            return Result.ok("成功,更新" + updateNum + "条数据！");
        }
    }


    /**
     * 完成取消收货
     *
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "完成取消收货 ", notes = "完成取消收货 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/finishCancelReceive")
    public Result finishCancelReceive(@RequestBody ReceiveVO entity, HttpServletRequest request) {
        try {
            Result result = iReceiveService.finishCancelReceive(entity);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 收货完成
     *
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "正常收货完成", notes = "正常收货成")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/finishReceiveInfo")
    public Result finishReceiveInfo(@RequestBody Receive entity, HttpServletRequest request) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        entity.setGroupCode(UserUtil.getBranchCode());
        Result result = iReceiveService.finishReceiveInfo(entity);
        return result;
    }

    /**
     * 收货完成
     *
     * @param entity
     * @return
     */
    @ApiOperation(value = "部分收货", notes = "部分收货")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PutMapping("/partFinishReceiveInfo")
    public Result partFinishReceiveInfo(@RequestBody Receive entity) {
        if (StringUtils.isBlank(entity.getCode())) {
            return Result.error(TipConst.CODE_NOT_EMPTY);
        }
        entity.setGroupCode(UserUtil.getBranchCode());
        return iReceiveService.partFinishReceiveInfo(entity);
    }

    /**
     * 删除 收货
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "删除 收货 ", notes = "删除 收货 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @DeleteMapping(value = "")
    public Result batchdel(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iReceiveService.batchdel(codes);
            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 作废收货单
     *
     * @param codes
     * @param request
     * @return
     */
    @ApiOperation(value = "作废收货单 ", notes = "作废收货单 ", produces = MediaTypes.JSON_UTF_8)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "codes", value = "codes", required = true, paramType = "query", dataType = "List")
    })
    @NeedLogin
    @PutMapping("/blank")
    public Result blank(@RequestParam List<String> codes, HttpServletRequest request) {
        try {
            iReceiveService.blank(codes);

            return Result.ok();
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 收货单、退货单 保存
     *
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "保存 收货单 ", notes = "保存 收货单 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/save")
    public Result save(@RequestBody @Validated(Receive.Save.class) Receive entity, HttpServletRequest request) {
        try {
            Result result = iReceiveService.localSave(entity);
            return result;
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 提交 收货单
     *
     * @param entity
     * @param request
     * @return
     */
    @ApiOperation(value = "提交 收货单 ", notes = "提交 收货单 ")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/check")
    public Result check(@RequestBody @Validated(Receive.Save.class) Receive entity, HttpServletRequest request) {
        try {

            return iReceiveService.check(entity);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 收货登记
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取收货登记", notes = "获取收货登记")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "收货code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Receive.class))
    @NeedLogin
    @GetMapping(value = "/checkIn/{code}")
    public Result checkIn(@PathVariable String code, HttpServletRequest request) {
        try {
            ReceiveVO entityVO = iReceiveService.getOneVOByCode(code);
            return Result.ok().data(entityVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取 可退货明细 列表
     *
     * @param deliveryCode 订单号
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 可退货明细 列表", notes = "获取 可退货明细 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "deliveryCode", value = "订单号", required = true, paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OutboundItemVO.class))
    @NeedLogin
    @GetMapping("/findRefundOutItems")
    public Result findRefundOutItems(@RequestParam String deliveryCode, HttpServletRequest request) {
        try {
            // 判断订单有效性： 是否存在
            Delivery delivery = iDeliveryService.getOne(new QueryWrapper<Delivery>().lambda()
                    .eq(Delivery::getGroupCode,UserUtil.getBranchCode())
                    .eq(Delivery::getCode, deliveryCode)
                    .eq(Delivery::getDeleted, "0"));
            if (delivery == null) {
                return Result.error("订单信息不存在，请确认");
            }

            // 获取可退订单列表
            List<DeliveryItemVO> canRefundItems = iDeliveryItemService.findCanRefundItems(deliveryCode);

            return Result.ok().data(canRefundItems);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取收货详情
     *
     * @param code
     * @param request
     * @return
     */
    @ApiOperation(value = "获取收货详情", notes = "获取收货详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "code", value = "收货code", paramType = "path", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = Receive.class))
    @NeedLogin
    @GetMapping(value = "/getDetailWithRegister/{code}")
    public Result getDetailWithRegister(@PathVariable String code, HttpServletRequest request) {
        try {
            ReceiveVO entityVO = iReceiveService.getVOByCode(code);
            return Result.ok().data(entityVO);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取 可退货入库单 列表， 发货退货单使用
     *
     * @param receiveDTO
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 可退货入库单 列表", notes = "获取 可退货入库单 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = DeliveryVO.class))
    @NeedLogin
    @GetMapping("/findReceiveCanRefundList")
    public Result findReceiveCanRefundList(ReceiveDTO receiveDTO, HttpServletRequest request) {
        try {
            // 根据仓库、入驻商、客户、已入库数量>退货数量, 单据类型为采购入库的 获取入货单列表
            List<Receive> receives = iReceiveService.list(new QueryWrapper<Receive>().lambda().eq(Receive::getWarehouseCode, receiveDTO.getWarehouseCode())
                    .eq(Receive::getGroupCode,UserUtil.getBranchCode())
                    .eq(Receive::getShipmentCode, receiveDTO.getShipmentCode())
                    .eq(StringUtils.isNotBlank(receiveDTO.getCustomerCode()), Receive::getCustomerCode, receiveDTO.getCustomerCode())
                    .eq(Receive::getType, ReceiveTypeEnum.RECEIVE.getValue())
                    .apply(" inbound_quantity > refund_quantity"));

            List<ReceiveVO> vos = receives.stream().map(e -> {
                ReceiveVO vo = new ReceiveVO();
                BeanUtil.copyProperties(e, vo);
                return vo;
            }).collect(Collectors.toList());

            return Result.ok().data(vos);
        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 获取 可退货明细 列表
     *
     * @param receiveCode 收货单号
     * @param request
     * @return
     */
    @ApiOperation(value = "获取 可退货明细 列表", notes = "获取 可退货明细 列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "receiveCode", value = "收货单号", required = true, paramType = "query", dataType = "String")
    })
    @ApiResponses(@ApiResponse(code = 0, message = "success", response = OutboundItemVO.class))
    @NeedLogin
    @GetMapping("/findReceiveRefundOutItems")
    public Result findReceiveRefundOutItems(@RequestParam String receiveCode, HttpServletRequest request) {
        try {
            List<ReceiveItemVO> canRefundItems = iReceiveService.findReceiveRefundItems(receiveCode);
            return Result.ok().data(canRefundItems);

        } catch (Exception e) {
            log.error(StrConsts.CATCH_MESSAGE, e);
            return Result.error(e.getMessage());
        }
    }


    /**
     * 收货导入预览
     *
     * @param filePath
     * @param isView
     * @param request
     * @return
     */
    @ApiOperation(value = "收货 导入 预览", notes = "收货 导入 预览")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importPreviewList")
    public Result importPreviewList(String filePath, Integer isView, HttpServletRequest request) {
        try {

            java.net.URL url = new java.net.URL(filePath);
            List<ReceiveItemExcelDTO> list = EasyExcelUtil.read(url.openStream(), ReceiveItemExcelDTO.class, 2);
            if (CollUtil.isEmpty(list)) {
                throw new ServiceException("文件内容为空");
            }
            List<ReceiveItemImportVO> locationList = iReceiveService.importPreviewList(list);
            return new Result().data(locationList);
        } catch (Exception e) {
            log.error("catch message:", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 预览后导入库位
     *
     * @param importCode 预览时生成的导入码
     * @param request
     * @return
     */
    @ApiOperation(value = "收货 导入", notes = "收货 导入")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer "),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000"),
            @ApiImplicitParam(name = "filePath", value = "文件路径", required = true, paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "isView", value = "是否已经预览", required = true, paramType = "query", dataType = "Integer")
    })
    @PostMapping("/importReceive")
    public Result importReceive(@RequestParam("importCode") String importCode, HttpServletRequest request) {
        try {
            Result result = iReceiveService.importReceive(importCode);
            return result;
        } catch (Exception e) {
            log.error("catch message:", e);
            return Result.error(e.getMessage());
        }
    }


    @ApiOperation(value = "手动确认奇门订单", notes = "手动确认奇门订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "授权token", required = true, paramType = "header", dataType = "String", defaultValue = "Bearer 123456"),
            @ApiImplicitParam(name = "deviceId", value = "设备id", paramType = "header", dataType = "string", defaultValue = "0000000000")
    })
    @NeedLogin
    @PostMapping("/orderConfirm/{code}")
    public Result orderConfirm(@PathVariable String code) {
        Inbound inbound = iInboundService.getOne(new LambdaQueryWrapper<Inbound>().eq(Inbound::getSourceCode, code).eq(Inbound::getGroupCode,UserUtil.getBranchCode()));
        if (null == inbound) {
            return Result.error("确认失败，找不到入库信息");
        }
        //推送奇门入库单确认信息,"0"-普通入库单 "1"-退货入库单
        iPutawayService.orderConfirm(inbound);

        return Result.ok("确认成功");
    }

}
